package ldh.im.fxgui.demo.controller;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import ldh.im.fxbase.util.FxThreadUtil;
import ldh.im.fxbase.util.StageUtil;
import ldh.im.fxbase.util.ThreadPoolUtil;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

public class DemoPaneController implements Initializable {

    @FXML private ListView<String> dataListView;

    private AtomicInteger atomicInteger = new AtomicInteger(0);
    private int limit = 1000;

    private Timer timer = new Timer();

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void close() {
//        timer.cancel();
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

        timer.scheduleAtFixedRate(new MyTimerTask(), 100, 100);
    }

    private void removeMore() {
        if (dataListView.getItems().size() > limit) {
            int size = dataListView.getItems().size() - limit;
            dataListView.getItems().remove(limit, size);
        }
    }

    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            boolean ishow = dataListView.getScene() != null && dataListView.getScene().getWindow() == StageUtil.getStage().getScene().getWindow();
            if (!ishow) timer.cancel();
            int idx =  atomicInteger.incrementAndGet();
            if (idx % 20 == 0) {
                System.out.println(String.format("%s add data, is show %s", name,  ishow));
            }
            if (dataListView == null) {
                close();
            }
            String data = "hello world " + idx;
            FxThreadUtil.runLater(()->{
                dataListView.getItems().add(data);
                removeMore();
                dataListView.getSelectionModel().select(dataListView.getItems().size()-1);
            });
        }
    }
}
